
package com.hlkj.pay.app.merchant.ext.impl.gtzfpay.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Ricky on 2016/11/20.
 */
@Slf4j
public class HttpUtils {

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, JSONObject jsonObject) {
        return post(url, jsonObject.toString());
    }
    public static String post(String url, Map<String, String> params) {
        return post(url, JsonUtils.toJsonString(params));
    }

    public static String post(String url, String json) {
        StringBuilder result = new StringBuilder();

        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);
            StringEntity reqEntity = new StringEntity(json, "UTF-8");

            // 设置POST请求的实体
            httpPost.setEntity(reqEntity);
            httpPost.setHeader("Content-Type", "application/json");
            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("国通支付返回参数 url:{}, params:{}, response:{}", httpPost.getURI(), json, result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}, params: {}", url, json, e);
        }
        return null;
    }

    /**
     * 发送 get请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String get(String url, JSONObject jsonObject) {
        StringBuilder result = new StringBuilder();
        // 创建默认的httpClient实例.
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String queryString = convertJSONToQueryParams(jsonObject);
            HttpGet httpGet = new HttpGet(url + "?" + queryString);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result.append(EntityUtils.toString(entity));
                }
            }
            log.info("国通支付返回参数 url:{}, response:{}", httpGet.getURI(), result);
            return result.toString();
        } catch (IOException e) {
            log.error("请求失败，url: {}", url, e);
        }
        return null;
    }

    public static String convertJSONToQueryParams(JSONObject jsonObject) throws UnsupportedEncodingException {
        StringBuilder queryParams = new StringBuilder();

        // 遍历JSONObject的所有键
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            if (value != null) {
                if (queryParams.length() > 0) {
                    queryParams.append("&");
                }
                // 使用URLEncoder来确保参数值是经过正确编码的
                queryParams.append(URLEncoder.encode(key, "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(value.toString(), "UTF-8"));
            }
        }

        return queryParams.toString();
    }

    public static void main(String[] args) {
        String key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApVrMRbefBfKIsbT7/zCrp1aWmsAc8RBxuqFasmiPQyRuISvkCTDdKmPWHmAF3n7MZckA3AiCrK5nhlvJ/79WLffgJ0d7aK+PhRk6Fokkuy/wIEEcgByVPV7Psb66SNa2Gq9MYASjCye/8S5ZfPUyHNjOFtSEIhbpOWm2+AoF4hd/87qe1pnTDT5TsB/QolLAacfR4QAwx2nhK2JyrzA+jdOgEi66HPBAN07DEX7bX4AX2q6EfVqYaqnQoQRKg+lxHDOq55XGQn+w91KKRf90fSYY91RpBg8RSf45vWFSLzTC9ZX5ybRSaeLZPONNtzm6HktMc1znwT/NRzH6SrDzzwIDAQAB";
//        String imageUrl = "http://jghwucyshtgjcbrnxgwe.gtxygroup.com/testterpay/yyfsevr/addCust/getBankInfo";
        String imageUrl = "http://jghwucyshtgjcbrnxgwe.gtxygroup.com/testterpay/yyfsevr/auth/wxApplySubmit";
         //{"agetId":"61000000339688","custId":"60000001045239","orderNo":"D20250327155024150198784","txamt":1,"openid":"oqA73649a-fae4q6Zz2zDVBxJhKY","payWay":"1","ip":"58.48.129.132","title":null,"driveNo":null,"wxAppid":"wx10305e7e481a6f0e","traType":"5","limitPay":null,"zfbappid":null,"zfbDisablePayChannels":null,"qrCode":null,"qrCodeType":null,"jdbtFqNum":null,"custLogin":null,"remark":"测试商品","operator":null,"latitude":null,"longitude":null,"spNo":null,"speakerSwitch":null,"fpid":null,"outTime":null,"asyncNotify":null,"realTimeRate":null,"realTimeD0Rate":null,"limitOpenid":null,"disInfo":null,"disTxamt":null,"codeAmt":null,"wxAttach":null,"timeStamp":"20250327155025","version":"1.0.0","sign":"hd9jlIRoi8IBsHlWuFTUdXpfsXDPm1OzkywYfXGZHw1hmGQvwEqMxEskrlvHgr85HGA7BSHgnTMOG7wU23hpa+YC4dxa6fYDXfxbzrLmVtul4nVKmhZScHdiEiBmEWPL09LU3TtfjlR/XR3R/2tLoBYcIJ0oyLYwGWJmSPmRtE/gm4EI2ZrZZyDZmdKN4d/3Mdlk0fqibi1jU2HtnCny6YPSUXTdId/j/MD/ME9BjP2QzGpTBcPrRyWz0rgNoF98fdedyhld1QK2Vg0H5qbY3O/YbkGPvcZZhscxO54d9AUCfhXfgwVPU7+ohSBgc1V2YCvyo8TVt2SrSZtcV1e2kA=="}
        try {
            Map<String, String> map = new LinkedHashMap<>();
            map.put("agetId", "61000000339688");
            map.put("custId", "60000001045301");
            map.put("timeStamp", DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN));
            map.put("version", "1.0.0");
            String sign = GtzfPayRsaUtil.encrypt(GtzfPayRsaUtil.getContent(JSONUtil.parseObj(map)), key);
            map.put("sign", sign);
            System.out.println(JSONUtil.parseObj(map).toString());
            System.out.println(HttpUtils.post(imageUrl, JSONUtil.parseObj(map)));
        } catch (Exception e) {
            throw new Runt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zZdDXBBdSFA9cp5pGa0h+XMJTcDrX4ViosqqenoE2ZP7lt1TKbAoNNNTfs5KaSt9bdnACHWqYV7\\/Lkdq5JykkeZ\\/edcN97UoXoOtGtmNPxVI2I2Vgo07tRmdxnxBfmhrpD3oWcMibfiE6T5vlLrXZvIK3CaWVcmTGX6ARLA5G7SkVPJs88faIPZVA7CVzuXknlNV5Q1wrW3tE10h8hWP6UqpLBie8Z3orjX+CuYZjlYN6WfmdOT8XolvbTV0XaRosGJHlb1uXuA+nleO3u0IWC7PTRjaUOruDKktYKwdI5pbjQdugrcNkJsdYQck2zm4jrsTGgD6zlBhJK5XjyZ4XWAFIxcGKSe91Lmt8R2A9dOPcbxVVCAszUEGOQ7OXBeWnXehTcJwz1THk4yLGES6L5UJAwqBoDkp\\/0mAJo4VQK7llhILCx1xEIVEPUCr54KN7FtVrEecZ95gaTKAc7TbXqK+3VoK7C59opexEdD3KbIXsCrsiujHDX+9K7s9XV7YkpPu70hVUl7m6DIuRLcy6qqwxoXdlrGXpD1rY7D7PIsgZy3Wd591G7Nbli0NB8PA+LRNwUgzCJOInGg3lVXBhQjNblg1tgw4nhYuwltAKni05gyNMr3xddN17hXDL+dG2MHynteZClxDq2ThvteWkFLfDQ=\",\"agetId\":\"61000000339688\"}";
//        JSONObject obj = JSONUtil.parseObj(json);
//        String plainText = GtzfPayRsaUtil.decrypt(obj.getStr("pdata"), key);
//        System.out.println(plainText);
//        System.out.println(GtzfPayRsaUtil.verify(plainText, key));
    }

}
